var idePerm;
var ideCheckList = []
$(function () {
  var roleId = getQueryString('roleId')
  $("#roleId").val(roleId)
  var url = api + "/admin/menu/tree";
  var options = {
    id: "menuTrees",
    url: url,
    check: {
      enable: true
    },
    expandLevel: 0,
    callBack: function (tree) {
    	$.operate.get(api + '/admin/menu/tree/' + roleId, function (res) {
    	      res.data.forEach(function (id) {
    	        var node = $._tree.getNodeByParam("id", id)
    	        $._tree.checkNode(node)
    	      })
    	}, false)
    }
  };
  $.tree.init(options);

  //获取ide权限/admin/ideperm/idepermission
  $.operate.get(api + '/admin/ideperm/idepermission/' + roleId, function (res) {
    idePerm = res.data
    var list = []
    Object.keys(res.data).forEach(function (item) {
      list.push(item)
      res.data[item].forEach(function (perm) {
        if (perm.assigned){
          ideCheckList.push(perm.id)
        }
      })
    })
    renderTpl('ideTpl', {list: list}, 'ideBox')
  }, false)
});

function submitHandler() {
  var roleId = $("#roleId").val();
  var selMenus = $.tree.getCheckedNodes();
  var data = {
    roleId: roleId,
    menuIds: selMenus,
    permissionIds: getIdePerms()
  }
  $.ajax({
    url: api + "/admin/role/menu",
    type: 'put',
    headers: {
      'content-type': 'application/json;charset=UTF-8'
    },
    data: JSON.stringify(data),
    success: function (res) {
      if (res.code == 0) {
        $.operate.successCallback(res);
      } else {
        $.modal.alertError(res.msg);
      }
    }
  })
}



function getIdePerms() {
  var chk_value = [];
  Object.keys(idePerm).forEach(function (item) {
    idePerm[item].forEach(function (perm) {
      if (perm.assigned){
        chk_value.push(perm.id)
      }
    })
  })
  return chk_value.join(',');
}


function permBtn(type) {
  $("#permBtnLayer").show();
  //根据type处理界面
//    debugger
//   var title = processPermData(type);
  var title = type
  loopData(type)
  layer.open({
    title: title + "分配权限",
    type: 1,
    closeBtn: false,
    shadeClose: false,
    area: ['750px', '400px'],
    content: $("#permBtnLayer"),
    btn: ['保存', '关闭', '全选'],
    yes: function () {
      savePermLayer(type);

    },
    btn3: function () {
      slecetedAllPerm();
      return false;
    },
    end: function () {
      $("#permBtnLayer").attr("style", "display:none;");
    }
  });
}

function slecetedAllPermNoLayer() {
  for (i = 0; i < list.length; i++) {
    list[i].checked = true;
  }
  showTips("已全部勾选！");
}

function slecetedAllPerm() {
  try {
    $('input[name="idePermCheck"]').each(function (index, item) {
      if (!$(this).is(":checked")) {
        $(this).click();
      }
    });
//        savePermLayer();
    layer.tips('全选成功！', '#permBtnLayer', {tips: [1, 'green'], area: ['260px', 'auto'], time: 2000});
  } catch (e) {
    layer.tips('全选失败！', '#permBtnLayer', {tips: [1, 'red'], area: ['260px', 'auto'], time: 2000});
  }
}

function savePermLayer(type) {
  //处理保存页面选中项保存
  try {
    $('input[name="idePermCheck"]').each(function (index, item) {
//        	debugger ideCheckList
      var item_ = $(item);
      var list = idePerm[type]
      for (i = 0; i < list.length; i++) {
        if (list[i].id == item_.val()) {
          if (item_.is(":checked")) {
            list[i].assigned = true;
          } else {
            list[i].assigned = false;
          }
        }
      }
      idePerm[type] = list
    });
    layer.tips('保存成功！', '#permBtnLayer', {tips: [1, 'green'], area: ['260px', 'auto'], time: 2000});
  } catch (e) {
    layer.tips('保存失败！', '#permBtnLayer', {tips: [1, 'red'], area: ['260px', 'auto'], time: 2000});
  }
}

function closePermLayer() {
//	savePermLayer();
  layer.closeAll('page'); //关闭所有页面层 1
}

function processPermData(type) {
  if ("create_" == type) {
    loopData("Create");
    return "创建";
  }
  if ("query_" == type) {
    loopData("Browse");
    return "查询";
  }
  if ("register_" == type) {
    loopData("Regist");
    return "注册";
  }
  if ("generate_" == type) {
    loopData("Generate");
    return "生成";
  }
  if ("delete_" == type) {
    loopData("Delete");
    return "删除";
  }
  if ("reference_" == type) {
    loopData("Ref");
    return "引用";
  }
  if ("pack_" == type) {
    loopData("Pack");
    return "打包";
  }
  if ("export_" == type) {
    loopData("Export");
    return "导出";
  }
  if ("update_" == type) {
    loopData("Update");
    return "更新";
  }
  if ("modify_" == type) {
    loopData("Modify");
    return "修改";
  }
  if ("compile_" == type) {
    loopData("Compile");
    return "编译";
  }
  if ("config_" == type) {
    loopData("Config");
    return "配置";
  }
  if ("deploy_" == type) {
    loopData("Deploy");
    return "部署";
  }
  if ("import_" == type) {
    loopData("Import");
    return "导入";
  }
  if ("debug_" == type) {
    loopData("Debug");
    return "调试";
  }
  if ("upload_" == type) {
    loopData("Upload");
    return "上传";
  }
  if ("saveas_" == type) {
    loopData("SaveAs");
    return "另存为";
  }
  if ("fastopen_" == type) {
    loopData("FastOpen");
    return "快捷键打开方式";
  }
}

function loopData(type) {
  $("#permContent").empty();
  var list = idePerm[type]
  for (i = 0; i < list.length; i++) {
    $("#permContent").append("<div style='width: 230px; float: left;margin-left: 10px;margin-top: 10px;'>" +
      "<label class='control-label' style='width: 130px; text-align: right; margin-right: 6px;'>" + list[i].permName.split("_")[1] + "</label>" +
      "<input type='checkbox' name='idePermCheck'" + (list[i].assigned ? ' checked=true ' : '') + " class='make-switch' data-size='mini' value='" + list[i].id + "' /></div>");

  }
}